package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.properties.TaskConfig;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.modular.rest.entity.RestDict;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.entity.Enum.PayStateEnum;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyPaymentOrderDetailsMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyWxMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyPaymentOrderAndYybbParam;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyPaymentOrderDetailsParam;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyPaymentOrderParam;
import cn.stylefeng.guns.sys.modular.system.model.result.AttendAuditBtyAreaAuditStatusResult;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyPaymentOrderAndYybbResult;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyPaymentOrderDetailsResult;
import  cn.stylefeng.guns.sys.modular.system.service.BtyPaymentOrderDetailsService;
import cn.stylefeng.guns.sys.modular.system.service.BtyPaymentOrderService;
import cn.stylefeng.guns.sys.modular.system.service.PushMsgService;
import cn.stylefeng.guns.sys.modular.system.service.WeChatSendTempMsgService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 店名日营业现金支付订单表 服务实现类
 * </p>
 *
 * @author wjk
 * @since 2021-12-07
 */
@Service
public class BtyPaymentOrderDetailsServiceImpl extends ServiceImpl<BtyPaymentOrderDetailsMapper, BtyPaymentOrderDetails> implements BtyPaymentOrderDetailsService {




    @Autowired
    private BtyPaymentOrderService btyPaymentOrderService;

    @Autowired
    private PushMsgService pushMsgService;

    @Resource
    private WeChatSendTempMsgService weChatSendTempMsgService;

    @Resource
    private BtyWxMapper btyWxMapper;

    @Resource
    private TaskConfig taskConfig;

    @Override
    public void add(BtyPaymentOrderDetailsParam param){
        BtyPaymentOrderDetails entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BtyPaymentOrderDetailsParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtyPaymentOrderDetailsParam param){
        BtyPaymentOrderDetails oldEntity = getOldEntity(param);
        BtyPaymentOrderDetails newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public BtyPaymentOrderDetailsResult findBySpec(BtyPaymentOrderDetailsParam param){
        return null;
    }

    @Override
    public List<BtyPaymentOrderDetailsResult> findListBySpec(BtyPaymentOrderDetailsParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtyPaymentOrderDetailsParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }


    /**
     * 获取分页查询支付的一些列表
     *
     * @author wjk
     * @Date 2021-12-08
     */
    @Override
    public LayuiPageInfo searchPayPageList(BtyPaymentOrderAndYybbParam btyPaymentOrderAndYybbParam) {
        String paidCashStartDate = generalGetSysDictPaidCashStartDateDay();

        String xjbzStartDate = generalGetSysDictXjbzStartDateDay();

        Page pageContext = getPageContext();
        IPage page = this.baseMapper.searchPayPageList(pageContext, btyPaymentOrderAndYybbParam,paidCashStartDate,xjbzStartDate);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 获取查询支付的列表，导出查询
     *
     * @author wjk
     * @Date 2021-12-14
     */
    @Override
    public List<BtyPaymentOrderAndYybbResult> searchPayList(BtyPaymentOrderAndYybbParam btyPaymentOrderAndYybbParam) {
        String paidCashStartDate = generalGetSysDictPaidCashStartDateDay();

        String xjbzStartDate = generalGetSysDictXjbzStartDateDay();

        List<BtyPaymentOrderAndYybbResult> list = this.baseMapper.searchPayList(btyPaymentOrderAndYybbParam,paidCashStartDate,xjbzStartDate);
        return list;
    }
    /**
     * 获取店长信息列表
     *
     * @author wjk
     * @Date 2021-12-14
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> searchMenDianList(BtyPaymentOrderAndYybbParam btyPaymentOrderAndYybbParam) {
        String paidCashStartDate = generalGetSysDictPaidCashStartDateDay();

        String xjbzStartDate = generalGetSysDictXjbzStartDateDay();

        //获取店名和妖码
        List<BtyPaymentOrderAndYybbResult> list= this.baseMapper.searchMenDianList(btyPaymentOrderAndYybbParam,paidCashStartDate,xjbzStartDate);
        Map<String,Object> map=new HashMap<>();

        //根据店名和妖码查询店长信息列表
        if(list.size()>0){
            List<BtyPaymentOrderAndYybbResult> resultList = this.baseMapper.searchDZList(list);
            map.put("code",0);
            map.put("msg","列表加载成功");
            map.put("count",list.size());
            map.put("data",resultList);
            return map;
        }
        map.put("code",0);
        map.put("msg","列表加载成功");
        map.put("count",0);
        map.put("data","");
        return map;
    }

    /**
     * 店内现金交账推送消息至小妖app和微信公众号
     *
     * @author ws
     * @Date 2022-03-03
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> xjjzPushMsgToIMAndWx(BtyPaymentOrderAndYybbParam btyPaymentOrderAndYybbParam) {
        // 正式环境的推送
        if (taskConfig.getRun().equals("y")) {
            String paidCashStartDate = generalGetSysDictPaidCashStartDateDay();

            String xjbzStartDate = generalGetSysDictXjbzStartDateDay();

            //获取店名和妖码
            List<BtyPaymentOrderAndYybbResult> listDY = this.baseMapper.searchMenDianList(btyPaymentOrderAndYybbParam, paidCashStartDate, xjbzStartDate);
            //根据店名获取店长信息
            List<BtyPaymentOrderAndYybbResult> list = this.baseMapper.searchDZList(listDY);


            //StringBuffer strBf = new StringBuffer();
            int listSize = list.size();
            String shopName = "";
            String yaoma = "";
            String phone = "";

            if (listSize>0) {
                for (int i = 0; i < listSize; i++) {
                    if (ToolUtil.isNotEmpty(list.get(i).getKqDh())) {
//                        shopName = shopName + list.get(i).getDianming();
//                        yaoma = yaoma + list.get(i).getYaoma();
//                        phone = phone + list.get(i).getKqDh();
//                        // 推送消息至畅聊
//                        pushMsgService.xjjzPushMsgToIM(shopName, yaoma, phone);
//                        // 推送消息至微信公众号
//                        xjjzPushMsgToWx(phone);

                        // 推送消息至畅聊
                        pushMsgService.xjjzPushMsgToIM(list.get(i).getDianming(), list.get(i).getYaoma(), list.get(i).getKqDh());
                        //  推送消息至微信公众号
                        xjjzPushMsgToWx(list.get(i).getKqDh());
                    }

                }
                Map<String, String> map = new HashMap<String, String>();
                map.put("flag", "true");
                map.put("message", "消息发送成功");
                map.put("data", "");
                return map;
            }else {
                Map<String, String> map = new HashMap<String, String>();
                map.put("flag", "false");
                map.put("message", "");
                map.put("data", "");
                return map;
            }


        }else {
            ///测试环境的推送
            String paidCashStartDate = generalGetSysDictPaidCashStartDateDay();

            String xjbzStartDate = generalGetSysDictXjbzStartDateDay();

            //获取店名和妖码
            List<BtyPaymentOrderAndYybbResult> listDY = this.baseMapper.searchMenDianList(btyPaymentOrderAndYybbParam, paidCashStartDate, xjbzStartDate);
            //根据店名获取店长信息
            List<BtyPaymentOrderAndYybbResult> list = this.baseMapper.searchDZList(listDY);


            //StringBuffer strBf = new StringBuffer();
            int listSize = list.size();
            String shopName = "";
            String yaoma = "";
            String phone = "";

            if (listSize>0) {
                // 推送消息至微信公众号
                xjjzPushMsgToWx(null);
                // 推送消息至畅聊
                pushMsgService.xjjzPushMsgToIM("半天妖临沂大学店", "0109003", null);
                Map<String, String> map = new HashMap<String, String>();
                map.put("flag", "true");
                map.put("message", "消息发送成功");
                map.put("data", "");
                return map;
            }else {
                Map<String, String> map = new HashMap<String, String>();
                map.put("flag", "false");
                map.put("message", "");
                map.put("data", "");
                return map;
            }
        }

    }


    /**
     * 店内现金交账发送消息至微信公众号
     * @author ws
     * @Date 2022-03-03
     */
    private void xjjzPushMsgToWx(String phone){

        //公众号消息提醒：“请打开小妖，进入【现金交账】及时缴纳现金"
        String data = ""+"请打开小妖，进入【现金交账】及时缴纳现金";
        JSONObject tempObj = weChatSendTempMsgService.setTempParam("门店", null, "现金交账提醒", "现金交账提醒",DateUtil.getNow(), data);



        //正式环境的推送
        if (taskConfig.getRun().equals("y")) {
            //正式环境的推送
            String dzMobile = phone;
            //获取受让方openid
            User user = btyWxMapper.getOpenId(dzMobile);
            String[] openid = null;
            if (ToolUtil.isNotEmpty(user)) {
                openid = new String[]{user.getOpenid()};
            }
            weChatSendTempMsgService.sendmsg(openid, null, tempObj);
        } else {
            //测试环境的推送
//            String dzMobile = "17686420611";
            //获取受让方openid
//            User user = btyWxMapper.getOpenId(dzMobile);
//            String[] openid = null;
//            if (ToolUtil.isNotEmpty(user)) {
//                openid = new String[]{user.getOpenid()};
//            }
            //测试号通知
            String[] openid = new String[]{"ovKAl6tEFItOkkzI4XO_44a0XHU4","ovKAl6iQnbWDrwtCPTDQ-iSU4TQA"};

            weChatSendTempMsgService.sendmsg(openid, null, tempObj);
        }

    }

    /**
     * 查询根据订单编号查询列表
     *
     * @author wjk
     * @Date 2021-12-09
     */
    @Override
    public LayuiPageInfo listByPayCode(BtyPaymentOrderDetailsParam btyPaymentOrderDetailsParam) {
        //若订单编号为空，则返回一个空的列表
        if(ToolUtil.isEmpty(btyPaymentOrderDetailsParam.getPayCode())){
            return new LayuiPageInfo();
        }

        String paidCashStartDate = generalGetSysDictPaidCashStartDateDay();

        Page pageContext = getPageContext();
        IPage page = this.baseMapper.listByPayCode(pageContext, btyPaymentOrderDetailsParam,paidCashStartDate);
        return LayuiPageFactory.createPageInfo(page);
    }


    /**
     * 根据yybb的id,和现金实缴，生成手动支付订单，生成手动支付的现金额度，手动支付现金额度；
     *
     * @author wjk
     * @Date 2021-12-09
     *
     *
     *
     * @updatDate 2022-01-07
     * @updat  新增店内充值金额，计算汇总
     */
    @Override
    public Map<String, String> btyPaymentOrderDetailsForPaidCash(BtyPaymentOrderDetailsParam btyPaymentOrderDetailsParam) {

        Map<String, String> map = new HashMap<String, String>();
        map.put("flag","false");
        // 首先，查询这个id 的yybb 的现金
        BtyPaymentOrderAndYybbResult btyPaymentOrderAndYybbResult  = getYybbById(btyPaymentOrderDetailsParam);
        // 查询，查询这个id 的订单详情，是不是已经有支付中，或者支付成功的订单
        BtyPaymentOrderDetails btyPaymentOrderDetails  = getBtyPaymentOrderDetailsByYybbId(btyPaymentOrderDetailsParam);
        if(ToolUtil.isNotEmpty(btyPaymentOrderDetails.getId())){
            //有已经支付成功的订单则直接返回
            if(btyPaymentOrderDetails.getPayState().equals(PayStateEnum.PAY_SUCCESS.getCode())){
                map.put("flag","false");
                map.put("msg","此订单已经被店内支付");
                return map;
            }

        }
        //对比这个支付订单的，xj 和传过来的paidcash 现金是否一致
        BigDecimal xj = btyPaymentOrderAndYybbResult.getXj();
        BigDecimal xjbz = btyPaymentOrderAndYybbResult.getXjbz();
        BigDecimal sumTodayCash = btyPaymentOrderAndYybbResult.getSumTodayCash();

        BigDecimal paidCash = btyPaymentOrderDetailsParam.getPaidCash();
        //天财现金和现金实缴一致
        if(sumTodayCash.compareTo(paidCash)==0){

        }else{
            map.put("flag","false");
            map.put("msg","输入的现金实缴("+paidCash+")，和店内应现金实缴("+sumTodayCash+")不一致。请确认现金实缴金额。");
            return map;
        }
        //生成订单号，生成订单
        //新建订单，将手动支付的订单存入，并且直接判定支付成功，支付人记录当前登录用户，支付方式为手动添加，增加手动支付人员信息和支付时间
        BtyPaymentOrder btyPaymentOrder = this.btyPaymentOrderService.addBtyPaymentOrderForPaidCash(btyPaymentOrderAndYybbResult);
        //若生成的支付订单失败，则判断失败
        if(ToolUtil.isEmpty(btyPaymentOrder.getPayCode())){
            map.put("flag","false");
            map.put("msg","生成手动支付订单失败");
            return map;
        }

        // 将新建的订单号，和支付详情存入支付详情。
        BtyPaymentOrderDetails btyPaymentOrderDetailsNew = addbtyPaymentOrderDetailsForPaidCash(btyPaymentOrderAndYybbResult,btyPaymentOrder);
        if(ToolUtil.isEmpty(btyPaymentOrderDetailsNew.getId())){
            map.put("flag","false");
            map.put("msg","生成手动支付订单失败");
            return map;
        }
        map.put("flag","true");
        map.put("msg","现金实缴增加成功");
        return map;
    }


    /**
     * 将新建的订单号，和支付详情存入支付详情。
     * @return
     *
     *
     *
     * @updatDate 2022-01-07
     * @updat  新增店内充值金额，计算汇总
     */
    private BtyPaymentOrderDetails addbtyPaymentOrderDetailsForPaidCash(BtyPaymentOrderAndYybbResult btyPaymentOrderAndYybbResult,  BtyPaymentOrder btyPaymentOrder) {

        BtyPaymentOrderDetails btyPaymentOrderDetails = new BtyPaymentOrderDetails();

        LoginUser sysLoginUser = LoginContextHolder.getContext().getUser();

        Date date = new Date();
        Long id = UUIDUtils.getId();

        btyPaymentOrderDetails.setYybbId(btyPaymentOrderAndYybbResult.getId());
        btyPaymentOrderDetails.setYyr(btyPaymentOrderAndYybbResult.getYyr());
        btyPaymentOrderDetails.setDm(btyPaymentOrderAndYybbResult.getDianming());
        btyPaymentOrderDetails.setYaoma(btyPaymentOrderAndYybbResult.getYaoma());

        btyPaymentOrderDetails.setXj(btyPaymentOrderAndYybbResult.getXj());
        btyPaymentOrderDetails.setXjbz(btyPaymentOrderAndYybbResult.getXjbz());
        btyPaymentOrderDetails.setPaidCash(btyPaymentOrderAndYybbResult.getSumTodayCash());

        btyPaymentOrderDetails.setPayCode(btyPaymentOrder.getPayCode());
        btyPaymentOrderDetails.setBtyPaymentOrderId(btyPaymentOrder.getId());
        btyPaymentOrderDetails.setPayState(btyPaymentOrder.getPayState());

        btyPaymentOrderDetails.setCreateUser(sysLoginUser.getId());
        btyPaymentOrderDetails.setCreateTime(date);
        btyPaymentOrderDetails.setUpdateUser(sysLoginUser.getId());
        btyPaymentOrderDetails.setUpdateTime(date);
        btyPaymentOrderDetails.setId(id);

        Boolean flag = this.save(btyPaymentOrderDetails);
        if(flag){
            return btyPaymentOrderDetails;
        }else{
            return new BtyPaymentOrderDetails();
        }

    }


    /**
     * 查询，查询这个id 的订单详情，是不是已经有支付中，或者支付成功的订单
     * @return
     *
     *
     */
    private BtyPaymentOrderDetails getBtyPaymentOrderDetailsByYybbId(BtyPaymentOrderDetailsParam btyPaymentOrderDetailsParam) {

        //构造条件
        LambdaQueryWrapper<BtyPaymentOrderDetails> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BtyPaymentOrderDetails::getYybbId, btyPaymentOrderDetailsParam.getId());
        queryWrapper.orderByDesc(BtyPaymentOrderDetails::getCreateTime);
        List<BtyPaymentOrderDetails> list = this.list(queryWrapper);
        BtyPaymentOrderDetails btyPaymentOrderDetailsOld = new BtyPaymentOrderDetails();
        if(list.size()>0){
            btyPaymentOrderDetailsOld = list.get(0);
        }
        return btyPaymentOrderDetailsOld;
    }

    /**
     * 根据营业报表的id 查询一条日营业报表数据
     * @return
     *
     *
     *
     *
     * @updatDate 2022-01-07
     * @updat  新增店内充值金额，计算汇总
     */
    private BtyPaymentOrderAndYybbResult getYybbById(BtyPaymentOrderDetailsParam btyPaymentOrderDetailsParam) {

        String xjbzStartDate = generalGetSysDictXjbzStartDateDay();

        List<BtyPaymentOrderAndYybbResult> list = this.baseMapper.getYybbListById(btyPaymentOrderDetailsParam,xjbzStartDate);
        if(list.size()>0){
            BtyPaymentOrderAndYybbResult btyPaymentOrderAndYybbResultOld = list.get(0);
            return btyPaymentOrderAndYybbResultOld;
        }else{
            return new BtyPaymentOrderAndYybbResult();
        }
    }

    /**
     * 获取从什么日期开始现金交账
     *
     * @author wjk
     * @Date 2021-11-26
     */
    @Override
    public String generalGetSysDictPaidCashStartDateDay(){
        List<RestDict> list = this.baseMapper.getSysDictPaidCashStartDateDay();
        String day = "2022-01-01";
        if(list.size()>0) {
            RestDict sysDict = list.get(0);
            if(ObjectUtil.isNotEmpty(sysDict)&&ObjectUtil.isNotEmpty(sysDict.getCode())){
                String code = sysDict.getCode();
                day = code;
            }
        }

        return day;
    }

    /**
     *
     *
     * 查询随行付账号分组
     * @author wjk
     * @Date 2022-07-04
     */
    @Override
    public List<BtyPaymentOrderConfigMugua> getSuixingfuShopNumList() {
        List<BtyPaymentOrderConfigMugua> list = this.baseMapper.getSuixingfuShopNumList();
        return list;
    }

    /**
     * 获取从什么日期开始充值金额交账
     *
     * @author wjk
     * @Date 2021-11-26
     */
    @Override
    public String generalGetSysDictXjbzStartDateDay(){
        List<RestDict> list = this.baseMapper.getSysDictXjbzStartDateDay();
        String day = "2022-01-01";
        if(list.size()>0) {
            RestDict sysDict = list.get(0);
            if(ObjectUtil.isNotEmpty(sysDict)&&ObjectUtil.isNotEmpty(sysDict.getCode())){
                String code = sysDict.getCode();
                day = code;
            }
        }

        return day;
    }
    private Serializable getKey(BtyPaymentOrderDetailsParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyPaymentOrderDetails getOldEntity(BtyPaymentOrderDetailsParam param) {
        return this.getById(getKey(param));
    }

    private BtyPaymentOrderDetails getEntity(BtyPaymentOrderDetailsParam param) {
        BtyPaymentOrderDetails entity = new BtyPaymentOrderDetails();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
